<template>
  <header class="header">
    <van-row style="padding: 16px 20px;">
      <van-col span="4" style="display: flex; align-items: center;">
        <router-link to="javascript:void(0)" class="back-button" @click="$router.go(-1)">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M15.41 7.41L14 6L8 12L14 18L15.41 16.59L10.83 12L15.41 7.41Z" fill="#000000"/>
          </svg>
        </router-link>
      </van-col>

      <van-col span="16">
        <span style="font-size: 18px; font-weight: bold; display: block; text-align: center;">背单词</span>
      </van-col>
    </van-row>
  </header>
  <div class="timer-display">本次学习时间：{{ todayStudyTime }} 分钟</div>
  <div class="word-container">
    <h1>{{ currentWord.word }}</h1>
    <p><strong>中文:</strong> {{ currentWord.chinese }}</p>
    <p><strong>例句 :</strong> {{ currentWord.exampleSentence1 }}</p>
    <van-button @click="fetchNewWord">下一个</van-button>
    <van-button @click="addToFavorites">收藏</van-button>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted, computed} from 'vue';
import {get, post} from "../../util/request.js";

const currentWord = ref({});

// 计时器相关变量
const startTime = ref(null);
const elapsedTime = ref(0);
const isTiming = ref(false);
// 开始计时
function startTimer() {
  startTime.value = new Date();
  isTiming.value = true;
  timer();
}

// 计时函数
function timer() {
  if (isTiming.value) {
    const currentTime = new Date();
    elapsedTime.value = Math.floor((currentTime - startTime.value) / 1000 / 60); // 转换为分钟
    setTimeout(timer, 1000); // 每秒更新一次
  }
}

// 清除计时器
function stopTimer() {
  isTiming.value = false;
}

// 组件挂载时启动计时
onMounted(() => {
  startTimer();
});

// 组件卸载时停止计时
onUnmounted(() => {
  stopTimer();
  updateDatabaseStudyTime();
});

// ...（原有的fetchNewWord和addToFavorites函数定义）

// 计算并返回显示的分钟数
const todayStudyTime = computed(() => elapsedTime.value);
async function fetchNewWord() {
  try {
    const response = await get('home/words/getRandomWord');
    currentWord.value = response.data;
    console.log(currentWord.value);
  } catch (error) {
    console.error('Error fetching word:', error);
  }
}

async function addToFavorites() {
  try {
    const response = await get(`home/wrong-questions/collectionWord/${currentWord.value.id}`);
    alert("收藏成功")
    // Optionally, you can update UI or show a message confirming the operation
  } catch (error) {
    console.error('Error adding to favorites:', error);
    // Handle error: show error message, log, etc.
  }
}

async function updateDatabaseStudyTime() {
  try {
    const response = await post(`home/study-time/updateStudyTime/${todayStudyTime.value}`);
    console.log('学习时间更新成功', response);
  } catch (error) {
    console.error('更新学习时间失败:', error);
  }
}
onMounted(() => {
  fetchNewWord();
});
</script>

<style scoped>
.word-container {
  text-align: center;
}
/* 新增 header 和 nav 的样式 */
</style>
